﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace XMLParser
{
    class Parser
    {
        public Parser( ClassObject root )
        {
            _root = root;
        }

        private ClassObject _root;

        /// <summary>
        /// Generates the CAA parser code.
        /// </summary>
        /// <param name="strXMLFile"></param>
        /// <param name="parentDir">Dir where the parser class is to be generated</param>
        /// <param name="buffer">Input Template class code of the parser</param>
        public void Stream( String strXMLFile, String parentDir, String buffer )
        {
            // create a writer and open the file
            String strFilePath = parentDir + "\\" + "Parser.cxx";

            TextWriter tw = new StreamWriter( strFilePath );

            String strContent = "<#assign xml = " + ClassObject.Box( strXMLFile ) + "?cap_first >";
            tw.WriteLine( strContent );

            tw.WriteLine( buffer );

            String strCode = _root.GenerateParserCode(parentDir) ;

            strContent = "\nHRESULT ${className}::Parse(CATUnicodeString & iXMLFile, ${baseName}" + _root._Name + " *& op" + _root._Name + ")  ";
            strContent += "\n{";
            strContent += "\nHRESULT hr = E_FAIL ; ";
            strContent += "\nCATIDOMElement_var spRoot; ";
            strContent += "\nhr = Read" + _root._Name + "( spRoot, op" + _root._Name + " ) ; ";
            strContent += @"
            if( FAILED(hr) ) 
            { 
                return hr;                
            } ";

            tw.WriteLine( strContent );

            tw.WriteLine( "\nreturn hr;" );
            tw.WriteLine( "}" );

            tw.WriteLine( strCode );

            // close the stream
            tw.Close();

        }
    }
}
